type DeptItem = {
  id?: number
  label?: string
  value?: number
  deptId: number
  deptName: string
  parentId: number
  children?: DeptItem[]
}

export const findDept = function (list: DeptItem[], target: number): DeptItem | void {
  for (let i = 0; i < list.length; i++) {
    const { deptId, children = [] } = list[i]
    if (deptId === target) {
      return list[i]
    } else {
      const result = findDept(children, target)
      if (result) {
        return result
      }
    }
  }
}

export const buildDeptTree = function (source: DeptItem[]) {
  for (let i = source.length - 1; i >= 0; i--) {
    const child = source[i]

    const { deptId, children = [] } = child
    child.id = deptId
    child.children = children.length ? children : undefined

    for (let j = 0; j < source.length; j++) {
      const parent = source[j]
      const target = findDept([parent], child.parentId)
      if (target) {
        target.children = [...(target.children || []), child]
        source.splice(i, 1)
      }
    }
  }
  return source
}

export const buildDeptList = function (source: DeptItem[]) {
  for (let i = source.length - 1; i >= 0; i--) {
    const child = source[i]

    const { deptId, deptName, children = [] } = child
    child.id = deptId
    child.label = deptName
    child.value = deptId
    child.children = children.length ? children : undefined

    for (let j = 0; j < source.length; j++) {
      const parent = source[j]
      const target = findDept([parent], child.parentId)
      if (target) {
        target.children = [...(target.children || []), child]
        source.splice(i, 1)
      }
    }
  }

  return source
}